package gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

import last.fm.LastFmTrackAddon;
import last.fm.MergeLastFmTracks;
import library.Library;
import library.LibraryCollectArtists;
import library.PlayList;
import localFiles.LocalArtistAddon;
import localFiles.LocalCollectArtists;
import localFiles.LocalTrackAddon;
import localFiles.PathExtractionPattern;
import net.miginfocom.swing.MigLayout;
import baseStructure.Base;
import baseStructure.ExtendedSearch;
import baseStructure.Log;
import baseStructure.SearchArtist;
import baseStructure.SearchTrack;
import baseStructure.SortedList;
import baseStructure.Track;

public class TestGUI extends JPanel implements Observer {
	private static final long serialVersionUID = -3670358764801544840L;
	
	private static JFrame frame;
	
	private JButton btnLoad, btnTest1, btnTest2, btnLastFm;
	
	private Tree tree;
	
	private JTextArea txtInfo = new JTextArea(7, 64);
	
	public TestGUI() {
		super(new MigLayout());
		
		tree = new Tree();
		tree.addObserver(this);
		
	    txtInfo.setEditable(false);  
	    txtInfo.setOpaque(false);      
	    txtInfo.setWrapStyleWord(true);  
	    txtInfo.setLineWrap(true);
			
	    btnLoad = new JButton("Folder import");
		btnLoad.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {				
				new FolderImport().execute();
			}
		});

		btnLastFm = new JButton("last.fm");
		btnLastFm.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {				
				doLastFm();
			}
		});

		btnTest1 = new JButton("Test1");
		btnTest1.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {				
				doTest1();
			}
		});

		btnTest2 = new JButton("Test2");
		btnTest2.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {				
				doTest2();
			}
		});
		
		
		add(new JScrollPane(txtInfo), "span 2, wrap, w 100%, hmin pref");
		add(new JScrollPane(tree.getTree()), "w 30%, growy, pushy, hmin 35%");
		add(new JScrollPane(PlaylistTable.get("default")), "wrap, w 70%, growy, pushy, hmin 35%");
		add(btnLoad, "span 2, split, center");
		add(btnLastFm);
		add(btnTest1);
		add(btnTest2);
		
		//new ImportLibrary().execute();
	}
	
	@Override
	public void update(Observable o, Object arg) {
		Tree changedTree;
		
		if (o instanceof Tree) {
			changedTree = (Tree) o;
		} else return;
		
		Object selection = changedTree.getSelected();
		
		if (selection instanceof Base) {
			txtInfo.setText(((Base) selection).getInfo());
		}
	}
	
	private static void doLastFm() {
		LastFmTrackAddon.getUserTopTracks("ragnvaldf", new String[] { "limit=2500" }, MergeLastFmTracks.getInstance());
		LastFmTrackAddon.getUserLovedTracks("ragnvaldf", new String[] { "limit=2500" }, MergeLastFmTracks.getInstance());
	}
	
	private static void doTest1() {
		SortedList<Track> list = new SortedList<>();
		Library.getInstance().getTracks(list, new SearchTrack());
		PlayList tracklist = Library.getInstance().playlists.get("default");
		for (Track track : list) {
			tracklist.append(track);
		}
	}
	
	private static void doTest2() {
		SearchArtist sa = new SearchArtist();
		sa.addSearch(new ExtendedSearch(LocalArtistAddon.ADDON_NAME, "file"));
		
		SearchTrack search = new SearchTrack(sa);
		search.addSearch(new ExtendedSearch(LastFmTrackAddon.ADDON_NAME, "lovedby"));
		search.addSearch(new ExtendedSearch(LocalTrackAddon.ADDON_NAME, "file"));
		
		
		SortedList<Track> list = new SortedList<>();
		Library.getInstance().getTracks(list, search);
		PlayList tracklist = Library.getInstance().playlists.get("default");
		for (Track track : list) {
			tracklist.append(track);
		}
		System.out.println("Total: " + list.size());
	}

	private static void initGui() {		
		frame = new JFrame("MusicLib");

		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowListener() {
            public void windowClosing(WindowEvent arg0) {
            	/*int answer = JOptionPane.CANCEL_OPTION;
            	
        		answer = JOptionPane.showConfirmDialog(frame, "Do you want to export the library?");
        		
        		if (answer == JOptionPane.YES_OPTION) {
        			try {
						Library.getInstance().exportLibrary();
					} catch (ExportException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
				
            	
            	if (answer != JOptionPane.CANCEL_OPTION)*/ System.exit(0);
            }
            public void windowActivated(WindowEvent e) {};
            public void windowClosed(WindowEvent e) {};
            public void windowDeactivated(WindowEvent e) {};
            public void windowDeiconified(WindowEvent e) {};
            public void windowIconified(WindowEvent e) {};
            public void windowOpened(WindowEvent e) {};
        });
 
        TestGUI newContentPane = new TestGUI();
        newContentPane.setOpaque(true);
        
        frame.setContentPane(newContentPane);
        frame.setPreferredSize(new Dimension(800, 600));
        
        frame.pack();
        // setLocationRelativeTo needs to be used after pack!
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
	
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
	        public void run() {
	            initGui();
	        }
	    });
	}
	
	/*private class ImportLibrary extends SwingWorker<Void, Void> {
		@Override
		protected Void doInBackground() {
			btnLoad.setEnabled(false);
			
			String libraryFile = System.getProperty("user.home") + File.separator + "artistlib" + File.separator + "artistlib.library.ser";
			Library.getInstance().setLibraryBackend(new SerializedLibraryBackend(new File(libraryFile)));
			
			Library.getInstance().backend.readAll();
			Library.getInstance().readArtistsFromBackend();
			
			btnLoad.setEnabled(true);
			return null;
		}
	}*/
	
	private class FolderImport extends SwingWorker<Void, Void> {
		@Override
		protected Void doInBackground() {
			JFileChooser chooser = new JFileChooser(); 
		    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		    int ret = chooser.showOpenDialog(frame);
		    
		    if (ret == JFileChooser.APPROVE_OPTION) {
		    	btnLoad.setEnabled(false);
				btnLoad.setText("Loading ...");
				PathExtractionPattern pattern = new PathExtractionPattern("" +
						"%artistname%/" +
							"%albumyear% - %albumname%:" +
							"[%albumyear%] %albumname%:" +
							"(%albumyear%) %albumname%:" +
							"%albumname% (%albumyear%):" +
							"%albumname% [%albumyear%]:" +
							"%albumname%/" +
								"%tracknum%. %trackname%.%extension%:" +
								"%artistname - %tracknum% - %trackname%.%extension%");
		    	long startTime = System.nanoTime();
		    	LibraryCollectArtists i = new LocalCollectArtists(Library.getInstance(), chooser.getSelectedFile(), pattern);
				while (!i.getStatus()) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) { }
				}
				Log.i(String.format("Time used: %.2fs", (System.nanoTime() - startTime)/1000000000.0));
		    }
		    
		    btnLoad.setEnabled(true);
			btnLoad.setText("Folder Import");
			
			
			
			return null;
		}
	}
}
